package com.hmdp.utils;

import com.hmdp.entity.Voucher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

// 全局唯一ID生成器
@Component
public class OnlyOneIDProducer {
    // 开始秒数，用来生成时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    /**
     * 根据前缀生成全局唯一ID
     * @param prefix
     * @return
     */
    public Long ProduceId(String prefix){
        // 1.获取本地日期
        LocalDateTime now = LocalDateTime.now();
        // 2.获取时间戳，从UTC到现在的秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 3.用这个秒数减去开始秒数作为最后的时间戳
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        // 4.将日期转换为redis中易于分层的格式
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 5.拼接key，由前缀 + 日期组成
        String key = "icr:" + prefix + ":" + date;
        // 6.访问redis
        Long increment = stringRedisTemplate.opsForValue().increment(key);

        return timeStamp << COUNT_BITS | increment;
    }

}
